package com.example.micro_property_springboot.config;

import com.example.micro_property_springboot.service.SysBackupRecordService;
import com.example.micro_property_springboot.service.SysParamService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 定时任务配置类
 * 实现系统自动备份等定时功能
 */
@Configuration
@EnableScheduling
public class ScheduledTaskConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskConfig.class);
    
    @Autowired
    private SysBackupRecordService backupRecordService;
    
    @Autowired
    private SysParamService sysParamService;
    
    /**
     * 自动数据库备份任务
     * 每天凌晨2点执行自动备份
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void autoBackup() {
        logger.info("开始执行自动数据库备份任务");
        try {
            // 检查是否启用了自动备份功能
            Boolean enableAutoBackup = sysParamService.getBooleanParam("sys.auto_backup.enable", true);
            if (!enableAutoBackup) {
                logger.info("自动备份功能已禁用");
                return;
            }
            
            // 执行自动备份
            backupRecordService.doAutoBackup();
            logger.info("自动数据库备份任务执行完成");
        } catch (Exception e) {
            logger.error("自动数据库备份任务执行失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 清理过期备份文件任务
     * 每周一凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 ? * MON")
    public void cleanExpiredBackups() {
        logger.info("开始执行清理过期备份文件任务");
        try {
            // 获取保留天数配置
            Integer keepDays = sysParamService.getIntParam("sys.backup.keep_days", 30);
            
            // 清理过期备份
            backupRecordService.cleanExpiredBackups(keepDays);
            logger.info("清理过期备份文件任务执行完成，保留天数: {}", keepDays);
        } catch (Exception e) {
            logger.error("清理过期备份文件任务执行失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 刷新系统参数缓存任务
     * 每小时刷新一次
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void refreshParamCache() {
        try {
            sysParamService.refreshParamCache();
            logger.info("系统参数缓存刷新完成");
        } catch (Exception e) {
            logger.error("系统参数缓存刷新失败: {}", e.getMessage(), e);
        }
    }
}